'use strict';

const db = uniCloud.database()
const postsCollection = db.collection('posts')

exports.main = async (event, context) => {
	try {
		const { title, content, images = [] } = event
		
		// 参数验证
		if (!title) {
			return {
				code: -1,
				msg: '标题不能为空',
				data: null
			}
		}
		
		if (!content) {
			return {
				code: -1,
				msg: '内容不能为空',
				data: null
			}
		}
		
		// 获取当前用户信息
		const userInfo = context.userInfo
		if (!userInfo) {
			return {
				code: -1,
				msg: '用户未登录',
				data: null
			}
		}
		
		// 创建帖子
		const postData = {
			title,
			content,
			images,
			userId: userInfo.uid,
			createTime: Date.now(),
			updateTime: Date.now(),
			viewCount: 0,
			likeCount: 0,
			commentCount: 0
		}
		
		const result = await postsCollection.add(postData)
		
		return {
			code: 0,
			msg: '创建成功',
			data: {
				_id: result.id
			}
		}
	} catch (error) {
		console.error('创建帖子失败', error)
		return {
			code: -1,
			msg: '创建失败',
			data: null
		}
	}
} 